package 剑指Offer._3140;

import general_class.TreeNode;

import java.util.*;

/**
 * @author yzh
 * @version 1.0
 * @date 2021/9/24 17:13
 * 从上到下打印二叉树III
 * 算法：二叉树  层次遍历
 */
public class _32_III {

    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> ans = new ArrayList<>();
        Deque<TreeNode> queue = new ArrayDeque<>();
        boolean flag = true;
        if (root != null) queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> tmp = new ArrayList<>(size);
            for (int i = 0; i < size; i++) {
                final TreeNode poll = queue.poll();
                tmp.add(poll.val);
                if (poll.left != null) queue.offer(poll.left);
                if (poll.right != null) queue.offer(poll.right);
            }
            if (!flag) Collections.reverse(tmp);
            ans.add(tmp);
            flag = !flag;
        }
        return ans;
    }

}
